<template>
  <view class="my-reviews-container">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 自定义导航栏 -->
    <view class="top-nav">
      <view class="nav-left" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="nav-center">
        <text class="nav-title">我的评价</text>
      </view>
      <view class="nav-right"></view>
    </view>

    <!-- 评价列表 -->
    <view class="reviews-list">
      <view 
        v-for="(review, index) in reviews" 
        :key="index"
        class="review-card"
      >
        <!-- 商家信息 -->
        <view class="merchant-header">
          <image 
            v-if="review.merchantLogo" 
            :src="review.merchantLogo" 
            class="merchant-logo"
            mode="aspectFill"
          />
          <view class="merchant-info">
            <text class="merchant-name">{{ review.merchantName }}</text>
            <text class="food-name">{{ review.foodName }}</text>
          </view>
        </view>

        <!-- 评分 -->
        <view class="rating-section">
          <StarRating :value="review.overallRating" :readonly="true" :size="32" />
          <text class="rating-text">{{ review.overallRating }}.0分</text>
        </view>

        <!-- 评价内容 -->
        <view v-if="review.content" class="review-content">
          <text class="content-text">{{ review.content }}</text>
        </view>

        <!-- 评价标签 -->
        <view v-if="review.tags && review.tags.length > 0" class="review-tags">
          <view 
            v-for="(tag, tagIndex) in review.tags" 
            :key="tagIndex"
            class="tag"
          >
            <text class="tag-text">{{ tag }}</text>
          </view>
        </view>

        <!-- 评价图片 -->
        <view v-if="review.images && review.images.length > 0" class="review-images">
          <image 
            v-for="(image, imgIndex) in review.images" 
            :key="imgIndex"
            :src="image"
            class="review-image"
            mode="aspectFill"
            @click="previewImage(review.images, imgIndex)"
          />
        </view>

        <!-- 商家回复 -->
        <view v-if="review.merchantReply" class="merchant-reply">
          <view class="reply-header">
            <text class="reply-icon">💬</text>
            <text class="reply-label">商家回复：</text>
          </view>
          <text class="reply-content">{{ review.merchantReply }}</text>
          <text class="reply-date">{{ formatDate(review.merchantReplyAt) }}</text>
        </view>

        <!-- 评价时间和操作 -->
        <view class="review-footer">
          <text class="review-date">{{ formatDate(review.createdAt) }}</text>
          <view class="review-actions">
            <button 
              v-if="canEdit(review.createdAt)"
              class="action-btn edit"
              @click="editReview(review)"
            >
              编辑
            </button>
            <button 
              v-if="canEdit(review.createdAt)"
              class="action-btn delete"
              @click="deleteReview(review)"
            >
              删除
            </button>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="!loading && reviews.length === 0" class="empty-state">
        <text class="empty-icon">📝</text>
        <text class="empty-text">暂无评价</text>
        <text class="empty-tip">快去订单页面评价吧~</text>
      </view>

      <!-- 加载更多 -->
      <view v-if="hasMore" class="load-more">
        <text class="load-more-text">{{ loadingMore ? '加载中...' : '上拉加载更多' }}</text>
      </view>

      <!-- 没有更多 -->
      <view v-if="!hasMore && reviews.length > 0" class="no-more">
        <text class="no-more-text">没有更多了</text>
      </view>
    </view>

    <!-- 自定义Modal -->
    <CustomModal ref="customModal" />
  </view>
</template>

<script>
import StarRating from '@/components/StarRating.vue';
import CustomModal from '@/components/CustomModal.vue';
import reviewService from '@/services/review.js';

export default {
  components: {
    StarRating,
    CustomModal
  },
  data() {
    return {
      statusBarHeight: 0,
      reviews: [],
      page: 1,
      pageSize: 20,
      hasMore: true,
      loading: false,
      loadingMore: false
    };
  },
  onLoad() {
    // 获取状态栏高度
    const systemInfo = uni.getSystemInfoSync();
    this.statusBarHeight = systemInfo.statusBarHeight || 0;

    this.loadReviews();
  },
  onReachBottom() {
    if (this.hasMore && !this.loadingMore) {
      this.loadMore();
    }
  },
  onPullDownRefresh() {
    this.page = 1;
    this.reviews = [];
    this.hasMore = true;
    this.loadReviews().then(() => {
      uni.stopPullDownRefresh();
    });
  },
  methods: {
    // 返回
    goBack() {
      uni.navigateBack();
    },

    // 加载评价列表
    async loadReviews() {
      if (this.loading) return;

      try {
        this.loading = true;

        const params = {
          page: this.page,
          size: this.pageSize
        };

        const res = await reviewService.getMyReviews(params);
        
        if (this.page === 1) {
          this.reviews = res.data.items;
        } else {
          this.reviews = [...this.reviews, ...res.data.items];
        }

        this.hasMore = this.reviews.length < res.data.total;
      } catch (error) {
        console.error('加载评价列表失败:', error);
        uni.showToast({ title: '加载失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },

    // 加载更多
    async loadMore() {
      if (this.loadingMore || !this.hasMore) return;

      this.loadingMore = true;
      this.page++;
      await this.loadReviews();
      this.loadingMore = false;
    },

    // 判断是否可以编辑（24小时内）
    canEdit(createdAt) {
      const created = new Date(createdAt);
      const now = new Date();
      const diff = now - created;
      return diff < 24 * 60 * 60 * 1000; // 24小时 = 86400000毫秒
    },

    // 编辑评价
    editReview(review) {
      // TODO: 跳转到编辑评价页面
      uni.showToast({ title: '编辑功能开发中', icon: 'none' });
    },

    // 删除评价
    deleteReview(review) {
      this.$refs.customModal.show({
        title: '确认删除',
        content: '确定要删除这条评价吗？',
        type: 'warning',
        confirmText: '删除',
        cancelText: '取消',
        onConfirm: async () => {
          try {
            uni.showLoading({ title: '删除中...' });
            
            await reviewService.deleteReview(review.id);
            
            uni.hideLoading();
            
            uni.showToast({ title: '删除成功', icon: 'success' });
            
            // 刷新列表
            this.page = 1;
            this.reviews = [];
            this.hasMore = true;
            this.loadReviews();
          } catch (error) {
            uni.hideLoading();
            console.error('删除评价失败:', error);
            uni.showToast({ 
              title: error.message || '删除失败', 
              icon: 'none' 
            });
          }
        }
      });
    },

    // 预览图片
    previewImage(images, index) {
      uni.previewImage({
        urls: images,
        current: index
      });
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      const now = new Date();
      const diff = now - date;
      
      // 一分钟内
      if (diff < 60000) {
        return '刚刚';
      }
      // 一小时内
      if (diff < 3600000) {
        return Math.floor(diff / 60000) + '分钟前';
      }
      // 一天内
      if (diff < 86400000) {
        return Math.floor(diff / 3600000) + '小时前';
      }
      // 一周内
      if (diff < 604800000) {
        return Math.floor(diff / 86400000) + '天前';
      }
      
      // 超过一周显示具体日期
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
};
</script>

<style scoped>
.my-reviews-container {
  min-height: 100vh;
  background: #F5F5F5;
  padding-bottom: 40rpx;
}

/* 导航栏 */
.top-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 30rpx;
  background: #FFFFFF;
  border-bottom: 1rpx solid #EEEEEE;
}

.nav-left, .nav-right {
  width: 120rpx;
}

.back-icon {
  font-size: 40rpx;
  color: #333333;
}

.nav-center {
  flex: 1;
  text-align: center;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333333;
}

/* 评价列表 */
.reviews-list {
  padding: 20rpx 30rpx;
}

.review-card {
  margin-bottom: 20rpx;
  padding: 30rpx;
  background: #FFFFFF;
  border-radius: 16rpx;
}

.merchant-header {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-bottom: 24rpx;
  padding-bottom: 24rpx;
  border-bottom: 1rpx solid #F5F5F5;
}

.merchant-logo {
  width: 80rpx;
  height: 80rpx;
  border-radius: 12rpx;
}

.merchant-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.merchant-name {
  font-size: 30rpx;
  font-weight: 600;
  color: #333333;
}

.food-name {
  font-size: 26rpx;
  color: #666666;
}

.rating-section {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 20rpx;
}

.rating-text {
  font-size: 28rpx;
  font-weight: 600;
  color: #FF6B6B;
}

.review-content {
  margin-bottom: 20rpx;
}

.content-text {
  font-size: 28rpx;
  color: #666666;
  line-height: 1.6;
}

.review-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-bottom: 20rpx;
}

.tag {
  padding: 8rpx 20rpx;
  background: #FFF5F5;
  border-radius: 20rpx;
}

.tag-text {
  font-size: 24rpx;
  color: #FF6B6B;
}

.review-images {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin-bottom: 20rpx;
}

.review-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
}

.merchant-reply {
  margin-bottom: 20rpx;
  padding: 20rpx;
  background: #F8F8F8;
  border-radius: 12rpx;
}

.reply-header {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-bottom: 12rpx;
}

.reply-icon {
  font-size: 28rpx;
}

.reply-label {
  font-size: 26rpx;
  font-weight: 600;
  color: #666666;
}

.reply-content {
  font-size: 26rpx;
  color: #666666;
  line-height: 1.5;
  display: block;
  margin-bottom: 8rpx;
}

.reply-date {
  font-size: 22rpx;
  color: #999999;
}

.review-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 20rpx;
  border-top: 1rpx solid #F5F5F5;
}

.review-date {
  font-size: 24rpx;
  color: #999999;
}

.review-actions {
  display: flex;
  gap: 16rpx;
}

.action-btn {
  padding: 12rpx 28rpx;
  font-size: 24rpx;
  border-radius: 20rpx;
  border: none;
  line-height: 1;
}

.action-btn.edit {
  background: #FFF5F5;
  color: #FF6B6B;
}

.action-btn.delete {
  background: #F5F5F5;
  color: #999999;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
  margin-bottom: 12rpx;
}

.empty-tip {
  font-size: 24rpx;
  color: #CCCCCC;
}

/* 加载更多 */
.load-more {
  text-align: center;
  padding: 40rpx 0;
}

.load-more-text {
  font-size: 26rpx;
  color: #999999;
}

.no-more {
  text-align: center;
  padding: 40rpx 0;
}

.no-more-text {
  font-size: 26rpx;
  color: #CCCCCC;
}
</style>

